import { defineStore } from 'pinia'
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'
import mainAppBridge from '../utils/mainAppBridge'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import router from '../router'
import { createPinia } from 'pinia'
import { useFileHistoryStore } from './fileHistory'
import { useFilePreviewStore } from './filePreview'
import { usePermissionStore } from './permission'
import { authCenterApi } from '../utils/api'

const pinia = createPinia()

export const useMainStore = defineStore('main', {
  state: () => ({
    // 管理员信息
    currentAdmin: {},
    
    // 用户信息（可能在某些场景需要）
    currentUser: {},
    
    // 网站信息
    webInfo: {
      webName: "",
      webTitle: [],
      notices: [],
      footer: "",
      backgroundImage: "",
      avatar: ""
    },
    mainAppData: null, // 存储主应用传递的数据
    userInfo: {},
    token: '',
    
    // 预览系统授权状态
    previewAuthorized: false,
    previewPassword: '',

    // 表情数据
    EMOJI: [],
    
    // 文件预览状态
    filePreview: {
      file: null,
      visible: false,
      preferredViewer: 'FilePreview' // 'FilePreview' 或 'DocumentViewer'
    },
    
    // 记忆最后一次选择的tab
    activeTab: 'papers'
  }),
  
  actions: {
    // 加载管理员信息
    loadCurrentAdmin(admin) {
      console.log('加载管理员信息:', admin);
      
      // 确保token被保存
      if (admin && admin.accessToken) {
        localStorage.setItem("userToken", admin.accessToken);
      }
      
      this.currentAdmin = admin;
      
      // 如果在微前端环境中，同步到主应用
      if (qiankunWindow.__POWERED_BY_QIANKUN__) {
        console.log('同步管理员信息到主应用');
        mainAppBridge.setCurrentAdmin(admin);
      }
    },
    
    // 加载用户信息
    loadCurrentUser(user) {
      this.currentUser = user;
    },
    
    // 加载网站信息
    loadWebInfo(webInfo) {
      if (typeof webInfo.webTitle === 'string') {
        webInfo.webTitle = webInfo.webTitle.split('');
      }
      if (typeof webInfo.notices === 'string') {
        try {
          webInfo.notices = JSON.parse(webInfo.notices);
        } catch (e) {
          webInfo.notices = [];
        }
      }
      this.webInfo = webInfo;
    },
    
    // 从主应用同步状态
    syncFromMainApp() {
      if (qiankunWindow.__POWERED_BY_QIANKUN__) {
        console.log('从主应用同步状态');
        const mainStore = mainAppBridge.getMainStore();
        if (mainStore && mainStore.state) {
          if (mainStore.state.currentAdmin) {
            this.currentAdmin = mainStore.state.currentAdmin;
            
            // 同步token
            if (mainStore.state.currentAdmin.accessToken) {
              localStorage.setItem("userToken", mainStore.state.currentAdmin.accessToken);
            }
          }
          if (mainStore.state.currentUser) {
            this.currentUser = mainStore.state.currentUser;
          }
          if (mainStore.state.webInfo) {
            this.loadWebInfo(mainStore.state.webInfo);
          }
        }
      }
    },
    
    // 清除管理员信息
    clearAdmin() {
      // this.currentAdmin = {};
      // localStorage.removeItem("userToken");
    },

    // 设置主应用传递的数据
    setMainAppData(data) {
      this.mainAppData = data;
      
      // 同步主应用的认证信息
      if (data && data.authToken) {
        this.token = data.authToken;
      }
      
      if (data && data.userInfo) {
        this.userInfo = data.userInfo;
      }
    },
    
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
    },
    
    // 设置token
    setToken(token) {
      this.token = token;
    },
    
    // 设置预览系统授权状态
    setPreviewAuthorized(status, password = '') {
      this.previewAuthorized = status;
      this.previewPassword = password;
    },
    
    // 清除用户数据
    clearUserData() {
      this.userInfo = {};
      this.token = '';
    },
    
    // 登录成功后的操作
    loginSuccess({ userInfo, token }) {
      this.setUserInfo(userInfo);
      this.setToken(token);
    },
    
    // 退出登录
    logout() {
      this.clearUserData();
    },
    
    // 跳转到登录页
    redirectToLogin(redirect) {
      // 清除管理员信息
      this.clearAdmin();
      
      // 准备跳转参数
      const query = redirect ? { redirect } : {};
      
      // 处理跳转逻辑
      if (qiankunWindow.__POWERED_BY_QIANKUN__) {
        // 在微前端环境中，使用history API导航
        const loginPath = '/login' + (redirect ? `?redirect=${encodeURIComponent(redirect)}` : '');
        window.history.pushState({}, '', loginPath);
        window.dispatchEvent(new PopStateEvent('popstate'));
      } else {
        // 独立运行时，使用Vue Router导航
        router.push({ path: '/login', query });
      }
    },
    
    // 处理未登录或登录过期的情况
    handleAuthError(message) {
      // 显示错误消息
      if (window.ElMessage) {
        window.ElMessage.error(message || '登录已过期，请重新登录');
      } else {
        console.error(message || '登录已过期，请重新登录');
      }
      
      // 获取当前路径作为重定向目标
      let currentPath = '/';
      try {
        // 安全地获取当前路径
        if (router && router.currentRoute && router.currentRoute.value) {
          currentPath = router.currentRoute.value.fullPath;
        } else if (window.location && window.location.pathname) {
          // 回退到使用window.location
          currentPath = window.location.pathname + window.location.search;
        }
      } catch (error) {
        console.error('获取当前路径失败:', error);
      }
      
      // 跳转到登录页
      this.redirectToLogin(currentPath);
    },
    
    // 设置文件预览
    setFilePreview(file, preferredViewer = 'FilePreview') {
      this.filePreview.file = file;
      this.filePreview.visible = !!file;
      this.filePreview.preferredViewer = preferredViewer;
    },
    
    // 清除文件预览
    clearFilePreview() {
      this.filePreview.file = null;
      this.filePreview.visible = false;
    },
    
    // 设置当前选中的tab
    setActiveTab(tab) {
      this.activeTab = tab;
    }
  },
  
  getters: {
    // 判断用户是否已登录
    isLoggedIn: (state) => !!state.token,
    
    // 获取用户信息
    getUserInfo: (state) => state.userInfo,
    
    // 获取token
    getToken: (state) => state.token,
    
    // 获取主应用数据
    getMainAppData: (state) => state.mainAppData,
    
    // 获取预览系统授权状态
    isPreviewAuthorized: (state) => state.previewAuthorized,
    
    // 判断是否为管理员
    isAdmin: (state) => {
      // 只有通过管理员登录的用户才是管理员
      return !!(state.currentAdmin && state.currentAdmin.accessToken);
    },
    
    // 获取文件预览状态
    getFilePreview: (state) => state.filePreview,
    
    // 获取当前选中的tab
    getActiveTab: (state) => state.activeTab
  },
  
  persist: {
    storage: localStorage,
    paths: ['currentAdmin', 'webInfo', 'previewAuthorized', 'previewPassword', 'filePreview.preferredViewer', 'activeTab']
  }
})

// 添加Auth Center相关状态
export const useAuthStore = defineStore('auth', {
  state: () => ({
    accessToken: localStorage.getItem('auth_token') || '',
    refreshToken: localStorage.getItem('refresh_token') || '',
    userInfo: JSON.parse(localStorage.getItem('user_info') || '{}'),
    isAuthenticated: !!localStorage.getItem('auth_token'),
  }),
  
  getters: {
    // 获取用户ID
    userId: (state) => state.userInfo.userId,
    
    // 获取用户名
    username: (state) => state.userInfo.username,
    
    // 获取用户角色
    roles: (state) => state.userInfo.roles || [],
    
    // 检查是否有特定角色
    hasRole: (state) => (role) => {
      return state.userInfo.roles?.includes(role) || false
    },
  },
  
  actions: {
    // 设置认证信息
    setAuth(authData) {
      this.accessToken = authData.accessToken
      this.refreshToken = authData.refreshToken
      this.userInfo = {
        userId: authData.userId,
        username: authData.username,
        roles: authData.roles
      }
      this.isAuthenticated = true
      
      // 保存到本地存储
      localStorage.setItem('auth_token', authData.accessToken)
      localStorage.setItem('refresh_token', authData.refreshToken)
      localStorage.setItem('user_info', JSON.stringify(this.userInfo))
    },
    
    // 更新访问令牌
    updateAccessToken(accessToken) {
      this.accessToken = accessToken
      localStorage.setItem('auth_token', accessToken)
    },
    
    // 清除认证信息
    clearAuth() {
      this.accessToken = ''
      this.refreshToken = ''
      this.userInfo = {}
      this.isAuthenticated = false
      
      // 清除本地存储
      localStorage.removeItem('auth_token')
      localStorage.removeItem('refresh_token')
      localStorage.removeItem('user_info')
    },
    
    // 登出
    async logout() {
      try {
        // 调用登出API
        await authCenterApi.logout()
      } catch (error) {
        console.error('登出错误:', error)
      } finally {
        // 无论API调用成功与否，都清除本地认证信息
        this.clearAuth()
      }
    }
  }
})

// 导出store
export * from './fileHistory'
export * from './filePreview'
export { useFileHistoryStore, useFilePreviewStore, usePermissionStore }
export default pinia 